#include "server.h"
#include "anet.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void acceptCommonHandler(int fd, int flags, char *ip) {
    client *c;
    c = createClient(fd);
}

void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    printf("accept from client\n");
    int cport, cfd;
    char cip[NET_IP_STR_LEN];

    cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport);
    printf("%d\n", cfd);
    acceptCommonHandler(cfd, 0, cip);
}

void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
    int nread, readlen;

    readlen = PROTO_IOBUF_LEN;
    char *buf = malloc(sizeof(char) * readlen);
    nread = read(fd, buf, readlen);
    if (nread > 0) {
        printf("%s\n", buf);
    }

    free(buf);
}

client *createClient(int fd) {
    client *c = malloc(sizeof(struct client));

    if (aeCreateFileEvent(server.el, fd, AE_READABLE,
        readQueryFromClient, c) == AE_ERR) {
        close(fd);
        free(c);
        return NULL;
    }

    return c;
}